package com.wandian.cqcsk.dialog;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.BaseBean;
import com.mylib.libcore.bean.UserInfoBean;
import com.mylib.libcore.config.CoinTypeEnum;
import com.mylib.libcore.network.rx.RxResultHelper;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.RetrofitUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.libcore.utils.crc.AESUtils;
import com.wandian.cqcsk.R;
import com.wandian.cqcsk.adapter.mine.SignInRecycleAdapter;
import com.wandian.cqcsk.bean.SignDataBean;
import com.wandian.cqcsk.data.BaseAppApi;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.mylib.libcore.config.NetConfig.BASE_SUCCESS_CODE;


/**
 * 签到弹框
 */
public class SignInDialogWindow extends PopupWindow {

    private SignInRecycleAdapter signInRecycleAdapter;
    private TextView tv_choose,tv_data;
    private View mMenuView;
    private RelativeLayout rl_sign_root;
    private RecyclerView recyclerView;
    private int isSign = 0;
    private Activity mActivity;
    public SignInDialogClink signInDialogClink;
    private BaseAppApi baseAppApi;
    private UserInfoBean userInfoBean;
    public interface  SignInDialogClink{
        void signInIvClink();
    }

    public void notifyTodaySignData(){
        this.isSign= 1;
        tv_choose.setText("已签到");
        tv_choose.setTextColor(mActivity.getResources().getColor(R.color.color_nine_seven));
        tv_choose.setBackground(mActivity.getResources().getDrawable(R.drawable.button_line_circle_ball));
        if(signInRecycleAdapter!=null)getSignList();
    }

    public SignInDialogWindow(Activity context,SignInDialogClink signInDialogClink) {
        super(context);
        baseAppApi = RetrofitUtil.getAppRetrofit().create(BaseAppApi.class);
        userInfoBean = AppContext.getInstance().getAppPreferencesHelper().getUserInfoBean();
        this.mActivity = context;
        this.isSign = userInfoBean.getIsSign();
        this.signInDialogClink =signInDialogClink;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.dialog_sign_in_view, null);
        tv_choose = (TextView) mMenuView.findViewById(R.id.tv_sign_in);
        tv_data = (TextView) mMenuView.findViewById(R.id.tv_data);
        rl_sign_root = (RelativeLayout) mMenuView.findViewById(R.id.rl_sign_root);
        recyclerView = (RecyclerView) mMenuView.findViewById(R.id.recycler);
        initRecycle(context);
        getSignList();
        if(isSign==1){
            tv_choose.setText("已签到");
            tv_choose.setTextColor(mActivity.getResources().getColor(R.color.color_nine_seven));
            tv_choose.setBackground(context.getResources().getDrawable(R.drawable.button_line_circle_ball));
        }
     //   设置按钮监听
        tv_choose.setOnClickListener(v -> {
            if(isSign==0)signInDialogClink.signInIvClink();
        });
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)this.setClippingEnabled(false);
        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.popwin_anim_style);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        //mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        rl_sign_root.setOnClickListener(v -> dismiss());
    }

    @Override
    public void showAsDropDown(View anchor) {
        if(Build.VERSION.SDK_INT >= 24) {
            Rect rect = new Rect();
            anchor.getGlobalVisibleRect(rect);
            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
            setHeight(h);
        }
        super.showAsDropDown(anchor);
    }

    @Override
    public void showAsDropDown(View anchor, int xoff, int yoff) {
        if(Build.VERSION.SDK_INT >= 24) {
            Rect rect = new Rect();
            anchor.getGlobalVisibleRect(rect);
            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
            setHeight(h);
        }
        super.showAsDropDown(anchor, xoff, yoff);
    }
    private void initRecycle(Context context){
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,7);
        recyclerView.setLayoutManager(layoutManager);
        List<Integer> datas = new ArrayList<>();
        //获取当前时间
        Calendar ca= Calendar.getInstance();
        tv_data.setText(ca.get(Calendar.YEAR)+"年"+(ca.get(Calendar.MONTH)+1)+"月");
        int today=ca.get(Calendar.DAY_OF_MONTH);
        Date date = new Date(System.currentTimeMillis());
        int dayNumber = getDaysOfMonth(date);
        if(!UIUtils.isEmpty(dayNumber)){
            for(int i=0;i<dayNumber;i++)datas.add(i+1);
        }
        signInRecycleAdapter = new SignInRecycleAdapter(R.layout.item_sign_in_view,today);
        recyclerView.setAdapter(signInRecycleAdapter);
        signInRecycleAdapter.setNewData(datas);
    }

    //获取本月天数
    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    //获取签到信息
    public void getSignList(){
        JsonObject jsonObject = new JsonObject();
        HashMap<String, String> hashMap = new HashMap<>();
        jsonObject.addProperty("wdk", AESUtils.getInstance().encrypt(hashMap));
        RxResultHelper.getHttpObservable(mActivity, baseAppApi.signList(jsonObject))
                .subscribe(new Observer<BaseBean<Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }
                    @Override
                    public void onNext(BaseBean<Object> bean) {
                        Log.d("signList",   JsonUtil.toJson(bean));
                        if(!UIUtils.isEmpty(bean) && bean.getCode()==BASE_SUCCESS_CODE){
                            try {
                                String json = AESUtils.getInstance().decrypt(bean.getData())+"";
                                Log.d("getCZList",   json);
                                if(!UIUtils.isEmpty(json) && json.length()>4){
                                    List<SignDataBean> listBean = JsonUtil.fromJson(json, new TypeToken<ArrayList<SignDataBean>>() {});
                                    if(listBean != null &&listBean.size()>0){
                                        signInRecycleAdapter.setSignListData(listBean);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}